package cn.yougou.serviceImpl;

import cn.yougou.common.DateUtil8;
import cn.yougou.common.DtoUtil;
import cn.yougou.dto.CommodityAllinone;
import cn.yougou.dto.Dto;
import cn.yougou.dto.Query;
import cn.yougou.mapper.YgCommodityMapper;
import cn.yougou.pojo.YgCategory;
import cn.yougou.pojo.YgCommodity;
import cn.yougou.pojo.YgCommodityProduct;
import cn.yougou.pojo.YgCommoditySpecification;
import cn.yougou.service.admin.YgAdminCategoryService;
import cn.yougou.service.admin.YgAdminCommodityService;
import cn.yougou.service.admin.YgAdminCpService;
import cn.yougou.service.admin.YgAdminCsService;
import cn.yougou.vo.YgCommodityVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import java.math.BigDecimal;
import java.util.*;

@Service
public class YgAdminCommodityServiceImpl implements YgAdminCommodityService {

    @Autowired
    private YgCommodityMapper ygCommodityMapper;

    @Autowired
    private YgAdminCsService ygAdminCsService;

    @Autowired
    private YgAdminCpService ygAdminCpService;

    @Autowired
    private YgAdminCategoryService ygAdminCategoryService;

    /**
     * 根据条件查询总条数（分页）
     * @param query
     * @return
     */
    @Override
    public int selCount(Query query) {
        return ygCommodityMapper.selCount(query);
    }

    /**
     * 查询全部商品 (分页)
     * @return
     */
    @Override
    public List<YgCommodityVo> findAllByQuery(Query query) {
        //实体类List
        List<YgCommodity> comList =  ygCommodityMapper.findAllByQuery(query);
        //VoList
        List<YgCommodityVo> comVoList = new ArrayList<>();
        //纯属无聊，转着玩,不想改mapper返回类型
        for(YgCommodity com : comList){
            YgCommodityVo ygCommodityVo = new YgCommodityVo();
            BeanUtils.copyProperties(com,ygCommodityVo);
            //计算折扣价
            ygCommodityVo.setDiscountAfter(
                    //调用计算折扣方法
                    this.calculate(com.getDiscount(),com.getCommoditymoney())
            );
            comVoList.add(ygCommodityVo);
        }
        return comVoList;
    }


    /**
     * 计算折扣价
     * 有折扣就计算，无折扣返回市场价
     */
    public double calculate(double discount ,double commoditymoney){
        //代表有折扣
        if(discount != -1){
            //将价格四舍五入到小数点后一位
            double priceAft = new BigDecimal(
                    commoditymoney*(discount/10)
            ).setScale(
                    1,BigDecimal.ROUND_HALF_UP
            ).doubleValue();
            return priceAft;
        }
        return commoditymoney;
    }

    /**
     * 添加商品
     * @return
     */
    @Override
    public Dto create(CommodityAllinone commodityAllinone) {
        Dto dto = null;
        //获取当前时间
        String nowTime = DateUtil8.getNowTime_EN();
        try {
            //1 商品表新增记录
            YgCommodity ygCommodity = commodityAllinone.getCommodity();
            ygCommodity.setCreatedate(nowTime);   //当前时间
            ygCommodity.setDeleted(1);             //删除逻辑
            ygCommodity.setSalesvolume(0);         //初始销量
            ygCommodity.setPageview(0);            //初始浏览量
            ygCommodity.setDiscount(ygCommodity.getDiscount() == null ? -1.0 : ygCommodity.getDiscount());
            int config = ygCommodityMapper.insert(ygCommodity);
            if(config > 0){
                //2 商品规格表新增记录
                YgCommoditySpecification[] csArray = commodityAllinone.getSpecifications();
                for(YgCommoditySpecification cs:csArray){
                    cs.setCommodityid(ygCommodity.getId());  //商品唯一id
                    cs.setAddtime(nowTime);//当前时间
                    cs.setDeleted(1);
                    ygAdminCsService.insert(cs);
                }
                // 3 商品规格组合表新增记录
                YgCommodityProduct[] cpList = commodityAllinone.getProducts();
                for(YgCommodityProduct cp:cpList){
                    cp.setCommodityid(ygCommodity.getId());  //商品唯一id
                    cp.setAddtime(nowTime);//当前时间
                    cp.setDeleted(1);
                    ygAdminCpService.insert(cp);
                }
            }
            dto = DtoUtil.returnSuccess();
        }catch (Exception e) {
            e.printStackTrace();
            dto =DtoUtil.returnFail("添加失败","50002");
        }
        return dto;
    }

    /**
     * 删除商品（实际上更改删除逻辑）
     * @param ygCommodity
     * @return
     */
    @Override
    public Dto delete(YgCommodity ygCommodity) {
        //1 删除商品记录
        ygCommodity.setDeleted(0);
        ygCommodityMapper.delete(ygCommodity);
        //2 删除商品规格记录
        YgCommoditySpecification ygCommoditySpecification = new YgCommoditySpecification();
        ygCommoditySpecification.setCommodityid(ygCommodity.getId());//把商品id给到其他两表的commodityid
        ygCommoditySpecification.setDeleted(0);
        ygAdminCsService.delete(ygCommoditySpecification);
        //3 删除商品规格组合记录
        YgCommodityProduct ygCommodityProduct = new YgCommodityProduct();
        ygCommodityProduct.setCommodityid(ygCommodity.getId());
        ygCommodityProduct.setDeleted(0);
        ygAdminCpService.delete(ygCommodityProduct);
        return DtoUtil.returnSuccess();
    }

    /**
     * 更新商品
     * @param commodityAllinone
     * @return
     */
    @Override
    public Dto update(CommodityAllinone commodityAllinone) {
        //获取当前时间
        String nowTime = DateUtil8.getNowTime_EN();
        //1 更新商品表
        YgCommodity ygCommodity = commodityAllinone.getCommodity();
        ygCommodity.setUpdatetime(nowTime); //当前时间
        ygCommodity.setDiscount(ygCommodity.getDiscount() == null ? -1.0 : ygCommodity.getDiscount()); //商品折扣
        int config = ygCommodityMapper.update(ygCommodity);
        if(config > 0){
            //2 更新商品规格表
            for (YgCommoditySpecification ygCs : commodityAllinone.getSpecifications()) {
                ygCs.setUpdatetime(nowTime);//当前时间
                ygAdminCsService.update(ygCs);
            }
            //3 更新商品规格组合表
            for (YgCommodityProduct ygCp : commodityAllinone.getProducts()) {
                ygCp.setUpdatetime(nowTime);//当前时间
                ygAdminCpService.update(ygCp);
            }
        }
        return DtoUtil.returnSuccess();
    }


    /**
     * 根据id获取商品信息，规格，规格组合
     * @param id
     * @return
     */
    @Override
    public Dto detail(Integer id) {
        YgCommodityProduct ygCp = null;
        YgCommoditySpecification ygCs = null;
        List<Integer> categoryIds = new ArrayList<>();
        Map<String,Object> detailMap = new HashMap();
        try {
            //1 商品表信息
            YgCommodity ygCommodity = ygCommodityMapper.queryById(id);
            if(null != ygCommodity) {
                //2 商品规格表信息
                ygCs = new YgCommoditySpecification();
                ygCs.setCommodityid(id);
                List<YgCommoditySpecification> csList = ygAdminCsService.queryList(ygCs);
                //3 商品规格组合表信息
                ygCp = new YgCommodityProduct();
                ygCp.setCommodityid(id);
                List<YgCommodityProduct> cpList = ygAdminCpService.queryList(ygCp);
                //4 商品父id
                YgCategory ygCategory =  ygAdminCategoryService.queryById(ygCommodity.getCategoryid());
                YgCategory ygCategory1 = ygAdminCategoryService.queryById(ygCategory.getPid());
                categoryIds.add(ygCategory1.getPid()); //一级分类
                categoryIds.add(ygCategory.getPid()); //二级分类
                categoryIds.add(ygCategory.getId());  //三级分类
                //5 处理Map集合
                detailMap.put("categoryIds",categoryIds); //商品三级类目父id
                detailMap.put("goods",ygCommodity);       //商品
                detailMap.put("specifications",csList);   //商品规格
                detailMap.put("products",cpList);         //商品规格组合
                return DtoUtil.returnDataSuccess(detailMap);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统出错","50001");
        }
        return DtoUtil.returnFail("没有该商品","50002");
    }







}
